package org.mybatis.generator.api.dom.jsp;

import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.dom.OutputUtilities;
import org.mybatis.generator.api.dom.xml.Element;

/**
 * JSP元素
 *
 * @author tangdelong 2015年6月17日
 */
public class JspElement extends Element {

	/**
	 * jsp元素名称
	 */
	private String name = "";

	/**
	 * jsp元素属性
	 */
	private List<JspAttribute> jspAttributes;

	/**
	 * jsp元素内中的元素
	 */
	private List<Element> jspElements;
	

	public JspElement(String name) {
		super();
		jspAttributes = new ArrayList<JspAttribute>();
		jspElements = new ArrayList<Element>();
		this.name = name;
	}

	@Override
	public String getFormattedContent(int indentLevel) {
		StringBuilder sb = new StringBuilder();

		// 是否缩进
		boolean isIndent = true;
		
		if(name.equalsIgnoreCase("head")){
			indentLevel--;
			isIndent = false;
		}else if(name.equalsIgnoreCase("meta")){
			indentLevel--;
			isIndent = false;
		}else if(name.equalsIgnoreCase("title")){
			indentLevel--;
			isIndent = false;
		}else if(name.equalsIgnoreCase("body")){
			indentLevel--;
			isIndent = false;
		}else if(name.equalsIgnoreCase("script")){
			indentLevel--;
			isIndent = false;
		}
		
		if(isIndent){
			// 缩进格式空4格
			OutputUtilities.jspIndent(sb, indentLevel);
		}
		
		sb.append('<');
		sb.append(name);

		for (JspAttribute att : jspAttributes) {
			sb.append(' ');
			sb.append(att.getFormattedContent());
		}

		// 标识是否是textElement元素, true为是
		boolean flag = false;
		if (jspElements.size() > 0) {
			sb.append(">"); 
			for (Element element : jspElements) {
				flag = false;
				if(element instanceof JspElement){
					OutputUtilities.newLine(sb);
					sb.append(element.getFormattedContent(indentLevel + 1));
				}
				if(element instanceof JspTextElement){
					sb.append(element.getFormattedContent(0));
					flag = true;
				}
			}
			
			
			if(!flag){
				OutputUtilities.newLine(sb);
			}
			
			if(!flag && isIndent){
				OutputUtilities.jspIndent(sb, indentLevel);
			}
			sb.append("</"); //$NON-NLS-1$
			sb.append(name);
			sb.append('>');

		} else {
			sb.append(" />"); //$NON-NLS-1$
		}

		return sb.toString();
	}

	
	public void addJspAttributes(JspAttribute jspAttribute){
		jspAttributes.add(jspAttribute);
	}

	public void addJspElements(Element jspElement){
		jspElements.add(jspElement);
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}
